package service

import (
	"user-center/dto"
	"user-center/entity"
	"user-center/query"
	"user-center/vo"

	"github.com/androidsr/sc-go/model"
	"github.com/androidsr/sc-go/sbuilder"
	"github.com/androidsr/sc-go/sc"
	"github.com/androidsr/sc-go/sgorm"
	"github.com/opentracing/opentracing-go/log"
)

type SysDictService struct {
}

func NewSysDictService() SysDictService {
	service := SysDictService{}
	return service
}

// 使用id获取数据
func (m SysDictService) Get(id string) vo.SysDictVO {
	data := new(entity.SysDict)
	data.Id = id
	err := sgorm.DB.GetOne(data)
	if err != nil {
		return vo.SysDictVO{}
	}
	return sc.Copy[vo.SysDictVO](data)
}

// 保存数据
func (m SysDictService) Save(dto *dto.SysDictDTO) error {
	data := sc.Copy[entity.SysDict](dto)
	err := sgorm.DB.Insert(data)
	return err
}

// 更新数据
func (m SysDictService) UpdateById(dto *dto.SysDictDTO) error {
	dbEntity := new(entity.SysDict)
	sgorm.DB.GetOne(dbEntity)
	sc.CopyTo(dto, dbEntity)
	err := sgorm.DB.UpdateById(dbEntity).Error
	return err
}

// 删除数据
func (m SysDictService) DeleteById(id string) error {
	err := sgorm.DB.DeleteById(entity.SysDict{}, id)
	return err
}

// 分页列表查询
func (m SysDictService) QueryPage(query *query.SysDictQueryDTO) *model.PageResult {
	sql := `select * from sys_dict a `
	data := make([]entity.SysDict, 0)
	b := sbuilder.StructToBuilder(query, sql)
	sql, values := b.Build()
	return sgorm.DB.SelectPage(&data, query.BaseQueryDTO.Page, sql, values...)
}

// 分页下拉查询
func (m SysDictService) QueryList(query *model.SelectQueryDTO) *model.PageResult {
	sql := `select a.id as value, a.group_name as label from sys_dict a where 1=1 `
	data := make([]model.SelectVO, 0)
	b := sbuilder.Builder(sql)
	b.Like("CONCAT(a.id,a.group_name)", query.Label)
	for k, v := range query.Vars {
		b.Eq(k, v)
	}
	b.Multiple().Ors(b.In("a.id", query.Selected))
	sql, values := b.Build()
	return sgorm.DB.SelectPage(&data, &query.Page, sql, values...)
}

func (m SysDictService) GetAll() any {
	data := make([]entity.SysDict, 0)
	err := sgorm.DB.Find(&data).Error
	if err != nil {
		log.Error(err)
		return err
	}
	result := make(map[string][]entity.SysDict, 0)
	var item []entity.SysDict
	for _, v := range data {
		item = result[v.GroupId]
		if item == nil {
			item = make([]entity.SysDict, 0)
		}
		item = append(item, v)
		result[v.GroupId] = item
	}
	return result
}
